<template>
  <div class="mainContent">
   <cardBox class="leftMenu" title="目录" icon="&#xe6f2;"> 
      <template #right>
        <el-select v-model="menuSelModel" @change="changeMenuSelModel" placeholder="请选择" size="small" style="width:160px">
          <el-option
            v-for="(item,index) in menuSeloptions"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </template>
      <div class="menu-tree">
        <treeMenu 
          :treeData="menuList" 
          name="lable" 
          ref="treeMenu" 
          nodeKey="id" 
          @menuLeftClick="handleMenuClick" 
          v-if="menuList.length > 0"
        />
        <noData showMenu v-else/>    
      </div>
    </cardBox>
    <div class="rightContent">
      <div class="boxWrapper tabbox">
        <el-tabs v-model="currentName" @tab-click="handleChangeTabs">
          <el-tab-pane label="埋设信息" name="1">
            <span slot="label"><i class="iconfont">&#xe777;</i> 埋设信息</span>
          </el-tab-pane>
          <el-tab-pane label="率定信息" name="2">
            <span slot="label"><i class="iconfont">&#xea44;</i> 率定信息</span>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div 
        class="tableContent boxWrapper" 
        v-loading="tableLoading" 
        element-loading-text="数据加载中，请稍后"  
        element-loading-spinner="el-icon-loading" 
        v-show="currentName == '1'"
      >
        <instrumentTable maxHeight="calc(100vh - 290px)" :tableList="tableList" @afterPasete="afterPasteData" @afterCellValueChange="afterCellChangeData" @cellDataChange="cellDataChange" 
        :showRoleCheck="permissions.showRoleCheck" 
        :enable-virtual-scroll="enableVirtualScroll" 
        @load-more="loadMoreData"              
        v-if="tableList.length > 0"></instrumentTable>

        <noData v-else showData></noData>

        <div class="btn-wrapper" v-if="tableList.length > 0">
          <span v-show="tableFormList.length > 0">💡温馨提示：您有未保存的修改，请及时保存！</span>
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-folder-checked" 
            :disabled="tableFormList.length <= 0" 
            @click="handleSaveTable"
          >
            保存信息
          </el-button>
        </div>
      </div>
      <calibration 
        v-if="currentName == '2'" 
        :stationId="stationId" 
        :treeId="treeId" 
        :menuSelModel="menuSelModel" 
        :treeNodeId="treeNodeID"
        :showRoleAdd="permissions.showRoleAdd"
        :showRoleEdit="permissions.showRoleEdit"
        :showRoleDel="permissions.showRoleDel"
      />
    </div>
  </div>
</template>

<script>
import cardBox from "../../components/base/cardBox.vue";
import treeMenu from '@/components/base/treeMenu.vue'
import calibration from '@/components/page/information/calibration.vue'
import { GetTreeStyle, GetTreeInstr, GetInstrInformationInPage, PointMonitor, setPowerPointBurys } from '../../api/https'
import bus from '@/utils/eventBus.js'
import noData from '@/components/base/noData.vue'
import instrumentTable from '@/components/page/information/instrumentTable.vue'
import permissionMixin from '@/utils/permission'
import { findLeafNodes } from '@/utils/treeUtils';
export default {
  name: 'instrument',
  mixins: [permissionMixin],
  components: { cardBox, treeMenu, calibration, noData,instrumentTable },
  data() {
    return {
      stationId: sessionStorage.getItem("stationId") || '',
      menuSeloptions: [],
      menuSelModel: '',
      menuList: [],
      defaultKey: 0,
      currentPage: 1,
      totalPage: 1,
      treeId: 0,
      treeNodeID: 0,
      currentName: '1',
      tableList: [],
      tableFormList: [],
      PointMonitorList: [],
      tableLoading: false,
      enableVirtualScroll:false,
    }
  },
  created() {
    this.initBasin()
    this.PointMonitorSelect()
    this.getMenuSelectOption()
  },
  activated() {
    this.initBasin()
    const newStationId = sessionStorage.getItem("stationId");
    if (this.stationId !== newStationId) {
      this.clearData()
      this.PointMonitorSelect()
      this.getMenuSelectOption()
    }
    if( this.currentPage < this.totalPage){
      this.enableVirtualScroll = true
    }
  },
  deactivated() {
    this.enableVirtualScroll = false
    bus.$off('station-changed', this.handleStationChanged);
  },
  beforeDestroy() {
    this.clearData()
  },
  computed: {
    permissions() {
        return this.getPermissions() || {}
    }
  },
  methods: {
    initBasin() {
      bus.$emit('showBasin', true);
      bus.$off('station-changed', this.handleStationChanged);
      bus.$on('station-changed', this.handleStationChanged);
    },
    handleStationChanged(newStationId, targetRoute) {
     if (!targetRoute || targetRoute === this.$route.name) {
        if (this.currentName === '1' && this.tableFormList.length > 0) {
          this.showSaveConfirm(() => {
            this.stationId = newStationId;
            this.clearData()
            this.PointMonitorSelect()
            this.getMenuSelectOption()
          })
        } else {
          this.stationId = newStationId;
          this.clearData()
          this.PointMonitorSelect()
          this.getMenuSelectOption()
        }
      }
    },
    showSaveConfirm(successCallback) {
      this.$confirm(`当前表格内容有修改尚未保存，离开前是否保存？？`, '提示',{
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
        cancelButtonClass: 'el-button--danger',
        type: 'warning'
      }).then(() => {
        this.handleSaveTable()
        successCallback && successCallback()
      }).catch(() => {
        this.onClearTable()
        successCallback && successCallback()
      });
    },
    
    clearData() {
      this.menuList = []
      this.tableList = []
      this.treeId = 0
      this.currentPage = 1
      this.totalPage = 1
      this.treeNodeID = 0
      this.tableFormList = []
      this.enableVirtualScroll = true
    },
    
    handleChangeTabs() {
      if (this.currentName === '2') {
        this.onConfirmSaveDataTip()
      }
    },
    
    changeMenuSelModel(val) {
      if (this.tableFormList.length > 0) {
        this.showSaveConfirm(() => {
          this.menuSelModel = val
          this.getMenuSelectOption()
        })
      } else {
        this.menuSelModel = val
        this.getMenuSelectOption()
      }
    },
    
    afterCellChangeData(row, column, changeValue) {
      const index = this.tableFormList.findIndex(item => item.id === row.id)
      if (index > -1) {
        this.tableFormList.splice(index, 1, row)
      } else {
        this.tableFormList.push(row)
      }
    },
    
    afterPasteData(data) {
      const { startRowIndex, endRowIndex } = data.selectionRangeIndexes
      const filterList = this.tableList.filter((item, index) => 
        index >= startRowIndex && index <= endRowIndex
      )
      
      if (this.tableFormList.length > 0) {
        const newFormList = this.tableFormList.filter(v => 
          !filterList.some(e => e.id === v.id)
        )
        this.tableFormList = [...newFormList, ...filterList]
      } else {
        this.tableFormList = [...filterList]
      }
    },
    
    getMenuSelectOption() {
      GetTreeStyle(this.stationId).then(res => {
        if (res.isSuccess && res.data?.length > 0) {
          this.menuSeloptions = res.data
          if (!this.menuSelModel) {
            this.menuSelModel = res.data[0]
          }
          this.getTreeData()
        } else {
          this.menuSeloptions = []
          this.menuSelModel = ''
        }
      })
    },
    
    getTreeData() {
      GetTreeInstr(this.stationId, this.menuSelModel).then(res => {
        if (res.isSuccess && res.data?.length > 0) {
          this.menuList = res.data
          const leafInfo = findLeafNodes(this.menuList);
          this.defaultKey = leafInfo.nodeId;
          this.treeId = leafInfo.node.node.treeid
          this.$nextTick(() => {
            this.$refs.treeMenu?.$refs.tree?.setCurrentKey(this.defaultKey)
            this.getDataList()
          })
        } else {
          this.clearData()
        }
      })
    },
    getDataList() {
      this.tableLoading = true
      const data = {
        treeId: this.treeId,
        statioN_ID: this.stationId,
        treeStyle: this.menuSelModel,
        pageIndex: this.currentPage,
        pageSize: 30
      }
      
      GetInstrInformationInPage(data).then(res => {
        this.tableLoading = false
        if (res.isSuccess) { 
          if (this.currentPage > 1) {
            this.tableList = this.tableList.concat(res.data.node)
          } else {
            this.tableList = res.data.node
          }
          this.totalPage = res.data.pagesNumber
          if( this.currentPage < this.totalPage){
              this.enableVirtualScroll = true
          }else{
              this.enableVirtualScroll = false
          }
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    
    cellDataChange(row, column, cellValue, type) {
      if (type === 'monitor') {
        const text = this.PointMonitorList.find(item => item.text === row.monitorText)
        row.monitorID = text?.id || ''
      }
      
      const index = this.tableFormList.findIndex(item => item.id === row.id)
      if (index > -1) {
        this.tableFormList.splice(index, 1, row)
      } else {
        this.tableFormList.push(row)
      }
    },
    
    PointMonitorSelect() {
      PointMonitor().then(res => {
        if(res.isSuccess && res.data?.length > 0){
          this.PointMonitorList = res.data
        }else{
          this.PointMonitorList = []
        }
      })
    },
    
    handleMenuClick(data) {
      this.treeId = data.treeid
      this.treeNodeID = data.id
      if (this.currentName === '1' && this.tableFormList.length > 0) {
        this.showSaveConfirm(() => {
            this.onClearTable() 
        })
      } else {
        this.onClearTable()
      }
    },
    
    handleSaveTable() {
      setPowerPointBurys(this.tableFormList).then(res => {
        if (res.isSuccess) {
          this.$message.success('保存成功!')
          this.tableFormList = []
        } else {
          this.$message.error(res.errorMessage)
        }
      })
    },
    
    onClearTable() {
      this.tableList = []
      this.currentPage = 1
      this.totalPage = 1
      this.enableVirtualScroll = true
      this.tableFormList = []
      this.getDataList()
    },
    onConfirmSaveDataTip() {
      if (this.tableFormList.length > 0) {
        this.showSaveConfirm()
      }
    },
    loadMoreData() {
        if (this.currentPage < this.totalPage) {
            this.currentPage++
            this.getDataList()
        }
    },
  }
}
</script>

<style scoped lang="scss">
.tabbox{
  padding: 0 20px;
  box-sizing: border-box;
  ::v-deep .el-tabs__header{
    margin-bottom: 6px;
  }
}
.mainContent{
  display: grid;
  grid-template-columns: 300px 1fr;
  height: calc(100vh - 95px);
  .leftMenu{
    width: 300px;
    height: calc(100vh - 120px);
    flex-shrink: 0;
    .menu-tree{
      height: calc(100vh - 200px);
      overflow-y: auto;
    }
  }
  .rightContent{
    height: calc(100vh - 120px);
    overflow: auto;
    margin: 0px 0 0 10px;
  }
}
.tableContent {
  margin-top: 10px;
  width: 100%;
  height: calc(100vh - 175px);
  padding: 10px;
  box-sizing: border-box;
}
.btn-wrapper {
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: end;

  span {
    line-height: 30px;
    margin-right: 20px;
    color: #f00
  }
}
</style>